<template>
  <div class="container">
    <div class="sidebar">
      <a-table
        :columns="MenuCount"
        :data="filteredTreeData"
        :pagination="false"
        @row-click="rowClickFunc"
        class="my-table"
      >
        <template #tr="{ record }">
          <tr :class="actRow === record.satelliteId ? 'my-tr' : ''"></tr>
        </template>
      </a-table>
    </div>
    <div class="main-content">
      <div>
        <a-button
          type="primary"
          @click="openModal"
          style="width: 100px; float: right; z-index: 99; margin-bottom: 20px; cursor: pointer"
        >
          新建
        </a-button>
      </div>
      <a-table :columns="columns" :data="data" row-key="id" align="center" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #action="{ record }">
          <div class="btnBox">
            <!-- <div class="lookBtn" @click="algorithmDetail(record)">
              绑定算法模型
            </div> -->
            <a-space>
              <a-button size="mini" type="text" @click="viewDetails(record)">
                <template #icon>
                  <IconEdit />
                </template>
                修改
              </a-button>
              <a-button status="danger" size="mini" type="text" @click="deleteDetail(record)">
                <template #icon>
                  <IconDelete />
                </template>
                删除
              </a-button>
            </a-space>
          </div>
        </template>
      </a-table>
      <a-pagination
        class="mt-2 float-right"
        :total="pagination.total"
        :current="pagination.pageNum"
        :page-size="pagination.pageSize"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      ></a-pagination>
    </div>
    <a-modal
      v-model:visible="showModal"
      :title="modalTitle"
      @before-ok="handleSubmit"
      class="modelCont"
      @cancel="handleCancel"
      :width="860"
    >
      <a-form :model="form" :rules="rules" ref="formRef" class="formData">
        <a-row>
          <a-col :span="24">
            <a-form-item label="遥测参数" field="selectData" required>
              <a-select v-model="form.selectData" placeholder="请选择遥测参数" allow-search :disabled="!!form.id">
                <a-option v-for="item in typeList" :value="JSON.stringify(item)" :key="item.code"
                  >{{ item.paramName }}({{ item.paramCode }})</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="参数上限" field="upperLimit" required>
              <a-input-number v-model="form.upperLimit" placeholder="请输入参数上限" :min="form.lowerLimit">
              </a-input-number
            ></a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="参数下限" field="lowerLimit" required>
              <a-input-number v-model="form.lowerLimit" placeholder="请输入参数下限" :max="form.upperLimit">
              </a-input-number
            ></a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="备注" field="remarks">
              <a-textarea v-model="form.remarks" placeholder="请输入算法描述" style="height: 120px"> </a-textarea
            ></a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="algorithmShow"
      title="绑定算法模型"
      @before-ok="algorithmHandleSubmit"
      class="modelCont"
      :width="1460"
    >
      <a-form :model="formAlgorithmData" ref="formAlgorithmShowRef" class="formData" :rule="arRules">
        <a-row>
          <a-col :span="12">
            <a-form-item label="算法模型" field="bindingType" required>
              <a-select v-model="formAlgorithmData.bindingType" placeholder="请选择算法模型">
                <a-option v-for="item in bindingTypeList" :value="item.value" :key="item.code">{{
                  item.label
                }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-table
          :columns="modelCoumns"
          :data="modelData"
          row-key="id"
          style="margin-top: 60px"
          align="center"
          :pagination="false"
          :row-selection="rowSelection"
          v-model:selectedKeys="formAlgorithmData.modelId"
        >
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table>
        <a-pagination
          class="mt-2 float-right"
          :total="modelPagination.total"
          :current="modelPagination.pageNum"
          :page-size="modelPagination.pageSize"
          @change="modelHandlePageChange"
          @page-size-change="modelHandlePageSizeChange"
          style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
        ></a-pagination>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { removeEmptyAndNull } from '@/utils/conmon'
import { apiHome } from '@/api'
import { Api } from '@/api/subscription'
import { Message, Modal } from '@arco-design/web-vue'
import * as echarts from 'echarts'
const searchQuery = ref('')
const satelliteId = ref('')
const rowSelection = {
  type: 'radio'
}
const treeData = ref([
  { id: 1, name: '卫星A', children: [{ id: 2, name: '子卫星A1' }] },
  { id: 3, name: '卫星B' }
])
const filteredTreeData = ref(treeData.value)
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const typeList = ref([])
const bindingTypeList = ref([
  { label: '多级门限预警', value: 1 },
  { label: '星座关联分析', value: 2 },
  { label: '复杂模型推理', value: 3 }
])
const data = ref([])
const actRow = ref(null)
const rules = {
  selectData: [{ required: true, message: '请选择遥测参数' }],
  upperLimit: [{ required: true, message: '请输入参数上限' }],
  lowerLimit: [{ required: true, message: '请输入参数下限' }]
}
const arRules = {
  bindingType: [{ required: true, message: '请选择算法模型' }]
}
const MenuCount = [
  {
    title: '卫星',
    dataIndex: 'satelliteName',
    align: 'center'
  }
]

const columns = [
  { title: 'ID', slotName: 'index' },
  { title: '卫星名称', dataIndex: 'satName' },
  { title: '参数名称', dataIndex: 'paramName' },
  { title: '参数识别码', dataIndex: 'paramCode' },
  { title: '参数上限', dataIndex: 'upperLimit' },
  { title: '参数下限', dataIndex: 'lowerLimit' },
  { title: '备注', dataIndex: 'remarks' },
  { title: '创建时间', dataIndex: 'createDate' },
  { title: '操作', slotName: 'action' }
]
const modelCoumns = [
  {
    title: '序号',
    slotName: 'index',
    width: 60,
    customRender: ({ index }) => {
      return index + 1 + (pagination.value.pageNum - 1) * pagination.value.pageSize
    }
  },
  { title: '告警名称', dataIndex: 'name' },
  { title: '卫星名称', dataIndex: 'satName' },
  { title: '参数名称', dataIndex: 'paramName' },
  { title: '参数识别码', dataIndex: 'paramCode' },
  {
    title: '一级门限警告值',
    children: [
      {
        title: '上限',
        dataIndex: 'firstLevelMaxValue'
      },
      {
        title: '下限',
        dataIndex: 'firstLevelMinValue'
      }
    ]
  },
  {
    title: '二级门限警告值',
    children: [
      {
        title: '上限',
        dataIndex: 'secondLevelMaxValue'
      },
      {
        title: '下限',
        dataIndex: 'secondLevelMinValue'
      }
    ]
  },
  {
    title: '三级门限警告值',
    children: [
      {
        title: '上限',
        dataIndex: 'thirdLevelMaxValue'
      },
      {
        title: '下限',
        dataIndex: 'thirdLevelMinValue'
      }
    ]
  },
  { title: '备注', dataIndex: 'remarks' },
  { title: '创建时间', dataIndex: 'createDate' }
]
const modelPagination = ref({ pageNum: 1, pageSize: 10, total: 0 })
const modelData = ref([])
const modelFetchPageList = () => {
  apiHome
    .getThresholdPageList({
      ...pagination.value,
      satelliteId: satelliteId.value
    })
    .then((res) => {
      console.log(res)
      modelData.value = res.data.list
      modelPagination.value.total = Number(res.data.total)
    })
}
modelFetchPageList()
const modelHandlePageChange = (page) => {
  modelPagination.value.pageNum = page
  modelFetchPageList()
}

const modelHandlePageSizeChange = (size) => {
  modelPagination.value.pageSize = size
  modelFetchPageList()
}

const formData = reactive({
  parameter: '',
  smoothing: '',
  taskName: ''
})
const formAlgorithmShowRef = ref(null)

const algorithmHandleSubmit = (done) => {
  console.log(formAlgorithmShowRef.value)
  formAlgorithmShowRef.value.validate().then((col) => {
    if (!col) {
      console.log('通过')
      console.log(formAlgorithmData.value)
      Api.algorithmModelBinding({ ...formAlgorithmData }).then((res) => {
        console.log(res)
      })
    } else {
      done(false)
      return false
    }
  })
}

const chart = ref(null)

const rowClickFunc = (record) => {
  console.log(record)
  actRow.value = record.satelliteId
  console.log(actRow.value)
  getEchatsData(actRow.value)
}
const onSearchChange = () => {
  console.log(searchQuery.value)
  if (searchQuery.value) {
    console.log(
      treeData.value.filter((node) => {
        // 确保返回布尔值
        return node.satelliteName.includes(searchQuery.value)
      })
    )
    filteredTreeData.value = treeData.value.filter((node) => {
      // 确保返回布尔值
      return node.satelliteName.includes(searchQuery.value)
    })
    console.log(filteredTreeData.value)
  } else {
    console.log(668)
    filteredTreeData.value = treeData.value
  }
}
const modalTitle = ref('新建健康监测遥测参数')
const showModal = ref(false)
const form = ref({
  selectData: '',
  dataSources: 1,
  deviceCode: '',
  deviceId: '',
  deviceName: '',
  lowerLimit: '',
  paramCode: '',
  paramId: '',
  paramName: '',
  remarks: '',
  satCode: '',
  satId: '',
  satName: '',
  subsystemId: '',
  subsystemName: '',
  upperLimit: ''
})
const formAlgorithmData = ref({
  bindingType: null,
  paramId: null,
  modelId: null
})
const openModal = () => {
  form.value = {
    selectData: '',
    dataSources: 1,
    deviceCode: '',
    deviceId: '',
    deviceName: '',
    lowerLimit: '',
    paramCode: '',
    paramId: '',
    paramName: '',
    remarks: '',
    satCode: '',
    satId: '',
    satName: '',
    subsystemId: '',
    subsystemName: '',
    upperLimit: ''
  }
  modalTitle.value = '新建健康监测遥测参数'
  showModal.value = true
}
const onSubmit = () => {
  // 模拟获取数据
  const data = [120, 200, 150, 80, 70, 110, 130]
  const categories = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

  const chartInstance = echarts.init(chart.value)
  chartInstance.setOption({
    xAxis: {
      type: 'category',
      data: categories
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data,
        type: 'line'
      }
    ]
  })
}
const getEchatsData = (id) => {
  satelliteId.value = id
  getSelectParams(id)
  fetchPageList()
}
const fetchPageList = () => {
  apiHome.getPageList({ ...pagination.value, satelliteId: satelliteId.value }).then((res) => {
    console.log(res)
    data.value = res.data.list
    pagination.value.total = Number(res.data.total)
  })
}
const getTabs = () => {
  apiHome.satellites().then((res) => {
    console.log(res)
    treeData.value = res.data
    onSearchChange()
    actRow.value = res.data[0].satelliteId
    satelliteId.value = res.data[0].satelliteId
    fetchPageList()
    getSelectParams(res.data[0].satelliteId)
  })
}
const formRef = ref(null)
const handleCancel = () => {
  showModal.value = false
  formRef.value.resetFields()
}
const handleSubmit = (done) => {
  // console.log(JSON.parse(form.value.selectData));
  formRef.value.validate().then((col) => {
    if (!col) {
      const apiMethod = form.value.id ? apiHome.updateSelectParams : apiHome.addParams
      apiMethod({
        ...removeEmptyAndNull({
          ...form.value,
          ...removeEmptyAndNull(JSON.parse(form.value.selectData))
        })
      }).then(() => {
        Message.success(form.value.id ? '修改成功' : '提交成功')
        showModal.value = false
        fetchPageList()
        done()
      })
    } else {
      done(false)
      return false
    }
  })
}

const deleteDetail = (record) => {
  Modal.confirm({
    title: '删除',
    content: `确定删除${record.paramName}参数吗？`,
    onOk: () => {
      apiHome.deleteOperatorMgr({ id: record.id }).then(() => {
        Message.success('删除成功')
        fetchPageList()
      })
    }
  })
}

const getSelectParams = (id) => {
  return apiHome.getSelectParams({ satId: id }).then((res) => {
    console.log(res)
    typeList.value = res.data
    return res.data // 确保返回数据
  })
}
const algorithmShow = ref(false)
const algorithmDetail = (record) => {
  console.log(record)
  formAlgorithmData.value.paramId = record.id
  algorithmShow.value = true
}

const viewDetails = async (record) => {
  modalTitle.value = '修改健康监测遥测参数'
  form.value = { ...record }
  form.value.upperLimit = Number(form.value.upperLimit)
  form.value.lowerLimit = Number(form.value.lowerLimit)

  try {
    const list = await getSelectParams(record.satId)
    list.forEach((item) => {
      if (item.paramId === record.paramId) {
        form.value.selectData = JSON.stringify(item)
      }
    })
    console.log(record)
    console.log(list)
    console.log(typeList.value)
    showModal.value = true
  } catch (error) {
    console.error('获取选择参数时出错：', error)
    // 在这里适当地处理错误
  }
}

const handlePageChange = (page) => {
  pagination.value.pageNum = page
  fetchPageList()
}

const handlePageSizeChange = (size) => {
  pagination.value.pageSize = size
  fetchPageList()
}

onMounted(() => {
  getTabs()
  chart.value = document.querySelector('#chart')
})
</script>

<style lang="less" scoped>
.btnBox {
  display: flex;
  div {
    margin-right: 10px;
    cursor: pointer;
  }
}
.lookBtn {
  color: #1d68d0;
}
.container {
  display: flex;
  min-height: calc(100vh - 56px);
}

.sidebar {
  width: 250px;
  padding: 20px;
  border-right: 1px solid #f0f0f0;
}
h2 {
  text-align: center;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei,
    serif;
  font-weight: bold;
  font-size: 18px;
  color: #222222;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.settings {
  margin-bottom: 20px;
}

.analysis {
  flex: 1;
}
.my-tr {
  background: #1d68d0;
  color: #fff;
  :deep(td) {
    background: #1d68d0;
    color: #fff;
  }
}
.my-tr :hover {
  background: #1d68d0;
  color: #fff;
}
.my-table tr {
  cursor: pointer;
}
</style>
